import { http } from "@/utils/http";
// import { getToken } from "@/utils/auth";
import { getToken175, getToken43 } from "@/utils/token";

type Result = {
  message: string;
  data: any;
  code: number;
};

// 为task API添加Authorization头的辅助函数
const taskRequest = <T>(method: string, url: string, data?: object) => {
  const token = getToken175(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

const remoteRequest = <T>(method: string, url: string, data?: object) => {
  const remoteToken = getToken43(); // 每次调用都获取最新的token
  return http.request<T>(method as any, url, {
    data,
    headers: {
      Authorization: remoteToken ? `Bearer ${remoteToken}` : undefined,
    },
  });
};

export const getDepartmentIp = (data?: object) => {
  return taskRequest<Result>("post", "/api/api/asset/department_ip", data);
};

// ==================== GitHub 快速查询相关接口 ====================

// GitHub 快速搜索接口
export const githubQuickSearch = (data?: {
  keywords: string[]; // 必填：搜索关键词数组
  logic?: "AND" | "OR"; // 可选：逻辑关系，默认 AND
  extensions?: string[]; // 可选：文件扩展名过滤
  exclude_keywords?: string[]; // 可选：排除关键词
  regex_pattern?: string; // 可选：正则表达式本地过滤
  per_page?: number; // 可选：每页数量，默认 30
}) => {
  return taskRequest<Result>("post", "/api/github/quick-search/", data);
};

// GitHub 确认入库接口
export const githubConfirmResults = (data?: {
  results: Array<{
    repository_url: string;
    file_path: string;
    matched_content: string;
  }>;
  department: string; // 必填：责任部门
}) => {
  return taskRequest<Result>(
    "post",
    "/api/pan/quick-search/batch-confirm",
    data
  );
};

// ==================== GitHub 任务管理相关接口 ====================

// 获取GitHub任务列表接口
export const getGithubTasks = (params?: {
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20
  status?: "pending" | "running" | "completed" | "failed"; // 状态过滤
  keyword?: string; // 关键词搜索（可选）
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/github/tasks", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取GitHub任务详情接口
export const getGithubTaskDetail = (taskId: number) => {
  return taskRequest<Result>("get", `/api/github/tasks/${taskId}`);
};

// 创建GitHub任务接口
export const createGithubTask = (data?: {
  task_name: string; // 必填：任务名称
  main_keyword: string; // 必填：主关键词
  description?: string; // 可选：描述
  scenario_types?: string; // 可选：场景类型 JSON 数组字符串
  schedule_enabled?: boolean; // 可选：是否启用调度
  cron_expression?: string; // 可选：Cron 表达式
}) => {
  return taskRequest<Result>("post", "/api/github/tasks", data);
};

// 更新GitHub任务接口
export const updateGithubTask = (
  taskId: number,
  data?: {
    task_name?: string;
    main_keyword?: string;
    description?: string;
    scenario_types?: string;
    schedule_enabled?: boolean;
    cron_expression?: string;
  }
) => {
  return taskRequest<Result>("put", `/api/github/tasks/${taskId}`, data);
};

// 删除GitHub任务接口
export const deleteGithubTask = (taskId: number) => {
  return taskRequest<Result>("delete", `/api/github/tasks/${taskId}`);
};

// 立即执行GitHub任务接口
export const executeGithubTask = (taskId: number) => {
  return taskRequest<Result>("post", `/api/github/tasks/${taskId}/execute`);
};

// 更新任务状态接口
export const updateTaskStatus = (
  taskCode: string | string[],
  status: "pause" | "resume"
) => {
  const taskCodes = Array.isArray(taskCode) ? taskCode : [taskCode];
  return taskRequest<Result>("post", "/api/pan/tasks/batch-update-status", {
    task_codes: taskCodes,
    status,
  });
};

// 删除任务接口
export const deleteTask = (taskCode: string) => {
  return taskRequest<Result>("delete", `/api/pan/tasks/${taskCode}`);
};

// 导出任务接口
export const exportTasks = (data?: {
  task_codes?: string[]; // 任务编码列表 (可选)
  format?: "xlsx" | "csv"; // 导出格式 (可选，默认xlsx)
}) => {
  const token = getToken175();
  return http.request<Blob>("post", "/api/pan/tasks/export", {
    data,
    responseType: "blob",
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== GitHub 缓存管理相关接口 ====================

// 获取GitHub缓存列表接口
export const getGithubCache = (params?: {
  task_id?: number; // 任务ID过滤（可选）
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/github/cache", {
    params,
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 确认缓存接口
export const confirmGithubCache = (data: {
  cache_keys: string[]; // 缓存key数组
  department: string; // 责任部门（必填）
}) => {
  return taskRequest<Result>("post", "/api/github/cache/confirm", data);
};

// 忽略缓存接口
export const ignoreGithubCache = (data: {
  cache_keys: string[]; // 缓存key数组
}) => {
  return taskRequest<Result>("post", "/api/github/cache/ignore", data);
};

// 手动清理缓存接口
export const cleanupGithubCache = () => {
  return taskRequest<Result>("delete", "/api/github/cache/cleanup");
};

// ==================== GitHub 资产管理相关接口 ====================

// 获取GitHub资产列表接口
export const getGithubAssets = (params?: {
  source_type?: string; // 来源类型，必须为 "github"
  department?: string; // 部门过滤（可选）
  risk_level?: "high" | "medium" | "low"; // 风险等级（可选）
  status?: "pending" | "confirmed" | "false_positive"; // 状态（可选）
  page?: number; // 页码，默认1
  per_page?: number; // 每页数量，默认20
  keyword?: string; // 关键词搜索（可选）
}) => {
  const token = getToken175();
  return http.request<Result>("get", "/api/pan/assets", {
    params: {
      source_type: "github", // 固定为 github
      ...params,
    },
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取资产详情接口
export const getGithubAssetDetail = (assetId: number | string) => {
  const token = getToken175();
  return http.request<Result>("get", `/api/asset/${assetId}`, {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// ==================== GitHub 知识图谱相关接口 ====================

// 统一知识图谱查询接口
export const getUnifiedGraphQuery = (data?: {
  center_node?: {
    type: string; // 中心节点类型: department, keyword, ip, asset, all
    value: string; // 中心节点值
  };
  domains?: string[] | string; // 数据域: ["pan_leak", "github_leak"] 或 "auto"
  max_depth?: number; // 最大深度: 1-3，默认 2
  time_range?: string; // 时间范围: 7d, 30d, 90d
  severity_filter?: string[]; // 风险等级: ["high", "critical"]
  limit?: number; // 返回节点数量限制，默认 50
}) => {
  return taskRequest<Result>("post", "/api/graph/unified/query", data);
};

// 获取可用节点列表接口
export const getUnifiedAvailableNodes = () => {
  const token = getToken175();
  return http.request<Result>("get", "/api/graph/unified/available_nodes", {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取数据域列表接口
export const getUnifiedDomains = () => {
  const token = getToken175();
  return http.request<Result>("get", "/api/graph/unified/domains", {
    headers: {
      Authorization: token ? `Bearer ${token}` : undefined,
    },
  });
};

// 获取节点详情接口
export const getUnifiedNodeDetail = (data?: {
  node_id: string; // 节点ID
  node_type: string; // 节点类型: department, user, repository, file, keyword 等
}) => {
  return taskRequest<Result>("post", "/api/graph/unified/node_detail", data);
};

// ==================== 旧接口（保留兼容）====================

// 获取GitHub图谱数据接口 - 已废弃，请使用 getUnifiedGraphQuery
export const getIntelligenceGraphData = (data?: {
  time_range?: string; // 时间范围: 7d, 30d, 90d, all
  limit?: number; // 限制节点数量
  severity_filter?: string[]; // 风险等级过滤
  keyword_filter?: string; // 关键词搜索（可选）
}) => {
  return taskRequest<Result>("post", "/api/github/graph/data", data);
};

// 获取节点详情接口 - 已废弃，请使用 getUnifiedNodeDetail
export const getNodeDetail = (data?: {
  node_id: string; // 节点ID
  node_type: string; // 节点类型: user, repository, file, keyword
}) => {
  return taskRequest<Result>("post", "/api/github/graph/node_detail", data);
};

// 获取部门列表接口
export const getDepartments = async () => {
  const result = await taskRequest<Result>(
    "get",
    "/api/pan/quick-search/departments"
  );

  if (result.code === 2000 && result.data?.departments) {
    // 处理部门列表：转换为 { label, value } 格式
    const departments = result.data.departments.map(
      (item: { department: string; persons: string[] }) => ({
        label: item.department,
        value: item.department,
      })
    );

    // 处理人员映射：以 department 为 key，value 是人员数组
    const personsMap: Record<
      string,
      Array<{ label: string; value: string }>
    > = {};
    result.data.departments.forEach(
      (item: { department: string; persons: string[] }) => {
        personsMap[item.department] = item.persons.map((person: string) => ({
          label: person,
          value: person,
        }));
      }
    );

    return {
      departments,
      personsMap,
    };
  }

  return result;
};
